package tree;

/**
 * 226. 翻转二叉树
 * 翻转一棵二叉树。
 */
public class InvertBinaryTree_226 {
    public TreeNode invertTree(TreeNode root) {
        return recurse(root);
    }

    public TreeNode recurse(TreeNode root) {
        if (root == null) {
            return null;
        }

        // 先记录左子树和右子树，递归之后在进行交换
        TreeNode left = recurse(root.left);
        TreeNode right = recurse(root.right);
        root.left = right;
        root.right = left;
        return root;
    }

    // 先交换，再递归
    public TreeNode invertTree2(TreeNode root) {
        if (root == null) {
            return null;
        }

        TreeNode tmp = root.left;
        root.left = root.right;
        root.right = tmp;
        invertTree2(root.left);
        invertTree2(root.right);
        return root;
    }
}
